package org.gzc.service.impl;

import org.gzc.dao.UserMapper;
import org.gzc.exception.LoginException;
import org.gzc.exception.RegisterException;
import org.gzc.pojo.User;
import org.gzc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = {Exception.class})
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User r_user) throws Exception {
        //查找用户是否已经注册
        if (userMapper.selectUserByEmailAndPassword(r_user.getEmail(), null) != null) {
            throw new RegisterException("邮箱已被注册！");
        }
        r_user.setAvatar("static/images/avatar/default.png");
        userMapper.insertSelective(r_user);
    }

    @Override
    public void Login(User l_user, HttpSession session) throws Exception {
        User user = userMapper.selectUserByEmailAndPassword(l_user.getEmail(), l_user.getPassword());
        if (user == null) {
            throw new LoginException("邮箱或密码错误！");
        }
        session.setAttribute("user", user);
    }

    @Override
    public List<User> getUserList(User user, Integer page, Integer limit) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", user.getId());
        param.put("nickname", user.getNickname());
        param.put("email", user.getEmail());
        param.put("sex", user.getSex());
        param.put("phone", user.getPhone());
        param.put("page", page);
        param.put("limit", limit);
        return userMapper.selectUserByPaging(param);
    }

    @Override
    public int getTotal() {
        return userMapper.getTotal();
    }

    @Override
    public int deleteUsers(List<User> users) {
        int num = 0;
        for (User user : users) {
            num += userMapper.deleteByPrimaryKey(user.getId());
        }
        return num;
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int addUser(User user) {
        return userMapper.insertSelective(user);
    }
}
